<?php
/************************************************************************
 Omnitrix - PHP Development Framework
 Copyright (C) 2012-2018 amonest(eastson@outlook.com)

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
************************************************************************/

function otx_module_path($module_name = null, $sub_path = null)
{
	if (empty($module_name)) {
		$module_name = otx_router_module();
	}

	if ('system' == $module_name) {
		$module_path = DIR_SYSTEM;
	} else {
		$module_path = DIR_MODULES . $module_name . DS;
	}

	if (empty($sub_path)) {
		return $module_path;
	} else {
		return $module_path . $sub_path;
	}
}

function otx_module_instance($module_name)
{
	global $_XMODULES;
	static $modules = array();

	if (array_key_exists($module_name, $modules)) {
		return $modules[$module_name];
	}

	$module_path = otx_module_path($module_name);
	if (!is_dir($module_path)) {
		throw new Exception('Module directory not exists: ' . $module_path);
	}

	$module_file = $module_path . DS. $module_name . '.php';
	if (!is_file($module_file)) {
		throw new Exception('Module file not exists: ' . $module_file);
	}

	require_once $module_file;

	$module_class = $module_name . '_module';
	if (!class_exists($module_class)) {
		throw new Exception('Module class not exists: ' . $module_class);
	}

	$instance = new $module_class();
	$instance->module_name = $module_name;
	$instance->module_path = $module_path;

	if (array_key_exists($module_name, $_XMODULES)) {
		$instance->module_id = $_XMODULES[$module_name]['module_id'];
		$instance->module_status = $_XMODULES[$module_name]['module_status'];
	}

	$modules[$module_name] = $instance;
	return $instance;
}

function otx_module_info($module_name)
{
	if (is_string($module_name)) {
		$instance = otx_module_instance($module_name);
	} else {
		$instance = $module_name;
	}

	$info = array(
		'name' => $instance->module_name,
		'title' => $instance->module_name,
		'description' => null,
		'website' => null,
		'email' => null,
		'author' => null,
		'version' => null
	);

	return array_merge($info, $instance->get_info());
}